package com.study.config;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

//@Configuration
public class RestConfig {
    @Bean
    public ClientHttpRequestFactory requestFactory() {
        SSLConnectionSocketFactory sslConnFactory = null;
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, authType) -> true).build();
            sslConnFactory = new SSLConnectionSocketFactory(sslContext,//
                    NoopHostnameVerifier.INSTANCE);
        } catch (Exception e) {
        }
        HttpClientBuilder builder = HttpClientBuilder.create().disableAutomaticRetries()//默认重试是开启的，建议关闭
                .evictIdleConnections(5, TimeUnit.MINUTES)//空闲连接5分钟关闭|每5分钟检查一次空闲连接
                .setConnectionTimeToLive(1, TimeUnit.MINUTES)//连接的TTL时间｜连接的最大存活时间是1分钟
                .setMaxConnTotal(100)//连接池大小
                .setMaxConnPerRoute(10);//每个主机的最大连接数
        if (sslConnFactory != null) {
            builder.setSSLSocketFactory(sslConnFactory);
        }

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(builder.build());
        return new BufferingClientHttpRequestFactory(factory);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.requestFactory(this::requestFactory)
                .setConnectTimeout(Duration.ofSeconds(5))
                .setReadTimeout(Duration.ofSeconds(10)).build();
    }
}
